import React, { useEffect, useState } from 'react'
import Navbar from '../../../compounts/navber/Navbar'
import { Avatar, Button, Tag, Toast, Input } from 'antd-mobile'
import { useSearchParams } from 'react-router-dom'
import { FillinOutline } from 'antd-mobile-icons'
import request from '../../../api/request'
import style from './detail.module.css'

function Index() {
    // 获取地址栏参数
    const [sp] = useSearchParams()
    const infoId = sp.get('id')
    // console.log('详情页ID:', infoId);

    // 存储医生数据
    const [doctorData, setDoctorData] = useState({}) // 修改为对象
    console.log(doctorData);
    
    // 存储评论内容
    const [commentData, setCommentData] = useState([])

    // 输入框数据
    const [value, setValue] = useState('')

    // 控制简介是否展开的状态
    const [isExpanded, setIsExpanded] = useState(false)
    
    // 检查是否已经评论过
    const [hasCommented, setHasCommented] = useState(false)


    // 获取医生详细资料
    const getDoctorDetail = () => {
        request.get('/user/inquiry/v1/findDoctorInfo', {
            params: {
                doctorId: infoId
            }
        }).then((res) => {
            console.log(res);

            setDoctorData(res.data.result || {})
            // 检查是否已经评论过
            checkCommentStatus()
        })
    }
    // 获取评论内容
    const getComment = () => {
        request.get('/user/inquiry/v1/findDoctorEvaluateList', {
            params: {
                doctorId: infoId,
                page: 1,
                count: 10
            }
        }).then((res) => {
            setCommentData(res.data.result || [])
            // 更新医生数据中的评论列表
            setDoctorData(prev => ({
                ...prev,
                commentList: res.data.result || []
            }))
        })
    }
    
    // 检查用户是否已经评论过该医生
    const checkCommentStatus = () => {
        const userId = localStorage.getItem('userId')
        if (!userId) return
        
        // 从本地存储检查是否评论过
        const commentedDoctors = JSON.parse(localStorage.getItem('commentedDoctors') || '[]')
        const hasCommented = commentedDoctors.includes(`${userId}_${infoId}`)
        setHasCommented(hasCommented)
    }
    
    // 记录用户评论状态到本地存储
    const recordCommentStatus = () => {
        const userId = localStorage.getItem('userId')
        if (!userId) return
        
        const commentedDoctors = JSON.parse(localStorage.getItem('commentedDoctors') || '[]')
        const key = `${userId}_${infoId}`
        
        if (!commentedDoctors.includes(key)) {
            commentedDoctors.push(key)
            localStorage.setItem('commentedDoctors', JSON.stringify(commentedDoctors))
        }
    }


    useEffect(() => {
        getDoctorDetail()
        getComment()
    }, [infoId])

    // 医生简介内容
    const doctorIntro = doctorData.doctorName ?
        `${doctorData.doctorName},${doctorData.jobTitle || '医师'}，从事外科工作35年余，毕业于哈尔滨医科大学，擅长甲状腺，乳腺疾病，肝，胆，胃肠疾病，阑尾炎，腹外疝，大隐静脉曲张下肢深静脉血栓诊治，腔镜下腹腔探查，胆囊结石，肝囊肿，阑尾，疝等腔镜微创手术。对外科急重症的抢救治疗，有丰富的临床经验。` :
        '加载中...'

    // 关注医生功能
    const handleFollow = async () => {
        try {
            const userId = localStorage.getItem('userId');
            const sessionId = localStorage.getItem('sessionId');

            if (!userId || !sessionId) {
                Toast.show('请先登录');
                return;
            }

            if (doctorData.followFlag == 1) {
                // 取消关注
                const response = await request.delete('/user/inquiry/verify/v1/cancelFollow', {
                    params: { doctorId: infoId },  // 参数放在params中
                    headers: { userId, sessionId }
                });
                // console.log(response);
                getDoctorDetail()
                if (response.data.status === 8001) {
                    Toast.show('已取消关注');
                } else {
                    Toast.show(response.data.message || '取消关注失败');
                }
            } else {
                // 关注医生
                const response = await request.post('/user/inquiry/verify/v1/followDoctor',
                    { doctorId: infoId },
                    { headers: { userId, sessionId } }
                );
                console.log(response);
                getDoctorDetail()

                if (response.data.status === 8001) {
                    Toast.show('关注成功');
                } else if (response.data.message && response.data.message.includes('不能重复关注')) {
                    Toast.show('不能重复关注');
                } else {
                    // 其他错误情况
                    Toast.show(response.data.message || '关注失败');
                }
            }
        } catch (error) {
            console.error('操作失败:', error);
            Toast.show('网络异常，请重试');
        }
    }

    // 发表评论功能
    const handleSendComment = async () => {
        try {
            // 验证输入内容
            if (!value.trim()) {
                Toast.show('请输入评论内容');
                return;
            }

            // 获取用户信息
            const userId = localStorage.getItem('userId');
            const sessionId = localStorage.getItem('sessionId');

            // 检查用户是否登录
            if (!userId || !sessionId) {
                Toast.show('请先登录');
                return;
            }

            // 检查是否已经评论过
            if (hasCommented) {
                Toast.show('您已经评论过该医生');
                return;
            }

            // 生成唯一的问诊ID (用户ID + 时间戳)
            const inquiryRecordId = parseInt(userId) * 10000000000 + new Date().getTime();

            // 调用评论接口
            const response = await request.put('/user/inquiry/verify/v1/evaluationInquiry',
                {
                    inquiryRecordId,
                    doctorId: infoId,
                    evaluate: value.trim(),
                    majorDegree: 5,  // 默认专业度5分
                    satisfactionDegree: 5  // 默认满意度5分
                },
                {
                    headers: {
                        userId: userId,
                        sessionId: sessionId
                    }
                }
            );
            console.log(response);
            
            if (response.data.status === 'success') {
                Toast.show('评论成功');
                // 清空输入框
                setValue('');
                // 记录评论状态
                recordCommentStatus();
                setHasCommented(true);
                // 刷新评论列表
                getComment();
            } else {
                Toast.show(response.data.message || '评论失败');
            }
        } catch (error) {
            console.error('发送评论失败:', error);
            Toast.show('网络异常，请重试');
        }
    }

    return (
        <div className={style.container}>
            <Navbar title={'医生详情'} style={{ backgroundColor: 'transparent', position: 'absolute', top: 0, left: 0, right: 0, zIndex: 10 }} />

            {/* 顶部渐变背景区域 */}
            <div className={style.header}>
                <h1 className={style.headerTitle}>人民好医生</h1>
                <Avatar className={style.headerAvatar} src={doctorData.imagePic} style={{ '--size': '100px' }} />
            </div>

            {/* 个人介绍区域 */}
            <div className={style.gerenjieshaoBox}>
                <div className={style.namebox}>
                    <div>
                        <h3>{doctorData.doctorName}</h3>
                        <span className={style.jobTitle}>{doctorData.jobTitle}</span>
                    </div>
                    <Button
                        color='primary'
                        fill={doctorData.followFlag == 1 ? 'solid' : 'outline'}
                        size='mini'
                        shape='rounded'
                        className={style.btn}
                        onClick={handleFollow}
                    >
                        {doctorData.followFlag == 1 ? '已关注' : '关注'}
                    </Button>
                </div>
                <p className={style.doctoryuan}>{doctorData.inauguralHospital}<Tag style={{ marginLeft: '10px' }}>三甲</Tag></p>

                {/* 折叠功能实现 */}
                <div className={`${style.jianjie} ${!isExpanded ? style.collapsed : ''}`}>
                    {doctorIntro}
                    {!isExpanded && (
                        <button className={style.expandBtn} onClick={() => setIsExpanded(true)}>
                            展开
                        </button>
                    )}
                    {isExpanded && (
                        <button className={style.collapseBtn} onClick={() => setIsExpanded(false)}>
                            收起
                        </button>
                    )}
                </div>
            </div>

            <div style={{ height: '15px', background: '#f7f7f7' }}></div>

            {/* 评论区域 */}
            <div className={style.commentSection}>
                <div className={style.commentHeader}>
                    <h3>患者评价 ({doctorData.commentList?.length || 0})</h3>
                    <FillinOutline />
                </div>

                <div className={style.inputbox}>
                    <Input
                        placeholder='请输入内容'
                        value={value}
                        onChange={val => {
                            setValue(val)
                        }}
                        style={{ width: '80%', borderRadius: '6px', background: '#e7e5e5ff' }}
                        disabled={hasCommented}
                    />
                    <Button size='small' color='primary' onClick={handleSendComment} disabled={hasCommented}>
                        {hasCommented ? '已评价' : '发表'}
                    </Button>
                </div>

                {doctorData.commentList?.length ? (
                    <ul className={style.commentList}>
                        {doctorData.commentList.map((comment, index) => (
                            <li key={index} className={style.commentItem}>
                                <div className={style.commentUserInfo}>
                                    <Avatar src={comment.headPic} style={{ '--size': '30px', borderRadius: '50%' }} />
                                    <div className={style.userInfoText}>
                                        <h5 className={style.userName}>{comment.nickName || '匿名用户'}</h5>
                                        <p className={style.commentTime}>{comment.commentTime}</p>
                                    </div>
                                </div>
                                <div className={style.commentContent}>
                                    {comment.content || '该用户未留下评论内容'}
                                </div>
                            </li>
                        ))}
                    </ul>
                ) : (
                    <div className={style.noComment}>
                        暂无评论
                    </div>
                )}
            </div>

            {/* 问诊按钮 */}
            <div className={style.wenzbtn}>
                <div>
                    500H币/次
                </div>
                <Button color='danger' fill='solid'>
                    立即问诊
                </Button>
            </div>
        </div>
    )
}

export default Index
